package com.taihua.transfer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.ConnectException;
import java.util.concurrent.TimeUnit;

public class ATSSocketClient {
    private static Channel socketChannel = null;
    public static ChannelFuture channelFuture = null;
    Bootstrap bootstrap = null;
    public void startConnect(String address,int port ) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();
            //bootstrap.option(ChannelOption.SO_BACKLOG,1024);
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(true))
                    .option(ChannelOption.TCP_NODELAY, Boolean.valueOf(true))
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Integer.valueOf(5000))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                            //socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
                            //socketChannel.pipeline().addLast(new SocketBufferEncoder(CharsetUtil.UTF_8));
                            //socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            //socketChannel.pipeline().addLast(new StdSocketClientHandler());

                            socketChannel.pipeline().addLast(new IdleStateHandler(5L, 0L, 30L, TimeUnit.SECONDS));
                            //socketChannel.pipeline().addLast(new SocketBufferEncoder());
                            //socketChannel.pipeline().addLast(new SocketBufferDecoder());
                            //socketChannel.pipeline().addLast(new SocketDataIntercept());
                            //socketChannel.pipeline().addLast(new SocketClientHandler());
                        }
                    });

            while(true){
                if (channelFuture == null) channelFuture = connect(address,port);
                if(socketChannel != null && socketChannel.isActive()){
                    System.out.println("on line");
                }else {
                    System.out.println("off line");
                    socketChannel = null;
                    channelFuture = null;
                }
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    ChannelFuture connect(String address,int port){
        try {
            ChannelFuture only =  bootstrap.connect(address, port).sync();
            only.addListener((GenericFutureListener) (future -> {
                if (future.isSuccess()) {
                    ATSSocketClient.socketChannel = only.channel();
                }
                if(future.isCancelled()){
                    ATSSocketClient.socketChannel.close();
                    ATSSocketClient.socketChannel.closeFuture();
                    ATSSocketClient.socketChannel = null;
                    ATSSocketClient.channelFuture = null;
                }
            }));
            return only;
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
        return null;
    }
}
